<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item :label="$t('ota.version.versionName')" prop="versionName">
                <el-input v-model="queryParams.versionName" :placeholder="$t('ota.version.placeholder.versionName')"
                          clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('common.button.query')}}</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('common.button.reset')}}</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['device:version:add']">{{$t('common.button.add')}}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['device:version:edit']">{{$t('common.button.edit')}}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['device:version:remove']">{{$t('common.button.remove')}}</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="versionList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column :label="$t('ota.version.versionNo')" align="center" prop="versionNo" />
            <el-table-column :label="$t('ota.version.deviceTypeName')" align="center" prop="deviceTypeName"></el-table-column>
            <el-table-column :label="$t('ota.version.deviceModelName')" align="center" prop="deviceModelName"></el-table-column>
            <el-table-column :label="$t('ota.version.versionType')" align="center" prop="versionType">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.firmware_type" :value="scope.row.versionType" />
                </template>
            </el-table-column>
            <el-table-column :label="$t('ota.version.versionInfo')" align="center" prop="versionInfo" />
            <el-table-column :label="$t('ota.version.originalFileName')" align="center" prop="originalFileName" />
            <el-table-column :label="$t('ota.version.versionUrl')" align="center" prop="versionUrl" width="220" :show-overflow-tooltip="true" />
            <el-table-column :label="$t('ota.version.versionState')" align="center" prop="versionState">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.versionState" :active-value="2" :inactive-value="1"
                        @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column :label="$t('common.table.operate')" fixed="right" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['device:version:edit']">{{$t('common.button.edit')}}</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['device:version:remove']">{{$t('common.button.remove')}}</el-button>
                </template>
            </el-table-column>
            <el-table-column :label="$t('ota.version.createTime')" align="center" prop="createTime" width="220" :show-overflow-tooltip="true" />
            <el-table-column :label="$t('ota.version.updateTime')" align="center" prop="updateTime" width="220" :show-overflow-tooltip="true" />
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

        <!-- 添加或修改【请填写功能名称】对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="140px">
                <el-form-item :label="$t('ota.version.deviceTypeName')" prop="deviceTypeId">
                    <el-select @change="deviceTypeChange" clearable v-model="form.deviceTypeId" :placeholder="$t('ota.version.placeholder.deviceTypeName')" :style="{ width: '100%' }">
                        <el-option v-for="dict in deviceTypeOptions"
                                   :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('ota.version.deviceModelName')" clearable prop="deviceModelId">
                    <el-select v-model="form.deviceModelId" :placeholder="$t('ota.version.placeholder.deviceModelName')" :style="{ width: '100%' }">
                        <el-option v-for="dict in deviceModelOptions"
                                   :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('ota.version.versionType')" prop="versionType">
                    <el-select v-model="form.versionType" :placeholder="$t('ota.version.placeholder.versionType')" :style="{ width: '100%' }">
                        <el-option v-for="dict in dict.type.firmware_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('ota.version.versionNo')" prop="versionNo">
                    <el-input v-model="form.versionNo" :placeholder="$t('ota.version.placeholder.versionNo')" />
                </el-form-item>
                <el-form-item :label="$t('ota.version.versionInfo')" prop="versionInfo">
                    <el-input v-model="form.versionInfo" :placeholder="$t('ota.version.placeholder.versionInfo')" />
                </el-form-item>
                <el-form-item :label="$t('ota.version.fileUpload')" prop="versionUrl">
                    <el-upload class="upload-demo" drag accept=".bin"  :headers="upload.headers"
                               :file-list="fileList"
                        :action="upload.url"  multiple :on-change="fileChange" :on-success='handleFileSuccess' :on-progress="handleFileUploadProgress" :data="form"
                                :auto-upload="true">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">{{$t('ota.version.uploadText')}}
                          <em>{{$t('ota.version.clickUpload')}}</em></div>
                        <div class="el-upload__tip" slot="tip" style="color: red;">{{$t('ota.version.uploadCheck')}}</div>
                    </el-upload>
                </el-form-item>

                <el-form-item :label="$t('ota.version.versionState')" prop="versionState">
                    <el-radio-group v-model="form.versionState">
                        <el-radio :label="2">{{$t('ota.version.enable')}}</el-radio>
                        <el-radio :label="1">{{$t('ota.version.disable')}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">{{$t('common.dialog.confirm')}}</el-button>
                <el-button @click="cancel">{{$t('common.dialog.cancel')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listVersion, getVersion, delVersion, addVersion, updateVersion, changeStatus } from "@/api/version/data";
import { typeTree } from "@/api/device/type";
import { modelTree } from "@/api/device/model";

export default {
    name: "Version",
    dicts: ['firmware_type'],
    data() {
        return {
            fileList: [],
            deviceTypeOptions: [],
            deviceModelOptions: [],
            // 按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 【请填写功能名称】表格数据
            versionList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                versionNo: undefined,
                versionInfo: undefined,
                versionUrl: undefined,
                versionState: undefined,
                deviceTypeId: undefined,
                deviceModelId: undefined,
                versionType: undefined,
            },
            // 表单参数
            form: {
            },
            // 表单校验
            rules: {
                versionId: [
                    { required: true, message: this.$t('ota.version.rules.versionId'), trigger: "blur" }
                ],
                versionNo: [
                    { required: true, message: this.$t('ota.version.rules.versionNo'), trigger: "blur" }
                ],
                versionInfo: [
                    { required: true, message: this.$t('ota.version.rules.versionInfo'), trigger: "blur" }
                ],
                versionUrl: [
                    { required: true, message: this.$t('ota.version.rules.versionUrl'), trigger: "blur" }
                ],
                versionState: [
                    { required: true, message: this.$t('ota.version.rules.versionState'), trigger: "blur" }
                ],
                deviceTypeId: [
                    { required: true, message: this.$t('ota.version.rules.deviceTypeId'), trigger: "change" }
                ],
                deviceModelId: [
                    { required: true, message: this.$t('ota.version.rules.deviceModelId'), trigger: "blur" }
                ],
                versionType: [
                    { required: true, message: this.$t('ota.version.rules.versionType'), trigger: "change" }
                ],
            },
            upload: {
                headers: { Authorization: "Bearer " + getToken() },
                url: process.env.VUE_APP_BASE_API + "/device/firmware/version/upload",
            },
            fileaddress: null,
            imageUrl: null
        };
    },
    created() {
        this.getList();
        this.getTypeTree();
    },
    methods: {
        deviceTypeChange(typeId) {
          if (typeId) {
            this.getModelTree(typeId)
          } else {
            this.form.deviceModelId = undefined
            this.deviceModelOptions = []
          }
        },
        getTypeTree() {
          typeTree().then(response => {
            this.deviceTypeOptions = response.data;
          });
        },
        getModelTree(typeId) {
          modelTree(typeId).then(response => {
            this.deviceModelOptions = response.data;
          });
        },
        /** 查询【请填写功能名称】列表 */
        getList() {
            this.loading = true;
            listVersion(this.queryParams).then(response => {
                this.versionList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.fileList = [];
            this.form = {
                versionId: undefined,
                versionNo: undefined,
                versionName: undefined,
                versionInfo: undefined,
                fileName: undefined,
                originalFileName: undefined,
                versionUrl: undefined,
                versionRelyNo: undefined,
                versionState: undefined,
                deviceType: undefined,
                deviceModel: undefined,
                versionType: undefined,
                versionFileSize: undefined,
                createdTime: undefined,
                modifiedTime: undefined
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
          this.form.versionFileSize = file.size
          this.form.originalFileName = file.name
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.versionId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.form.versionState = 1
            this.title = this.$t('common.operate.type.add') + this.$t('ota.version.moduleName');
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const versionId = row.versionId || this.ids
             getVersion(versionId).then(response => {
                this.deviceTypeChange(response.data.deviceTypeId)
                const uploadData = {
                  name: response.data.originalFileName,
                  url: response.data.versionUrl
                }
                this.fileList.push(uploadData)
                this.form = response.data;
                this.loading = false;
                this.open = true;
                this.title = this.$t('common.operate.type.edit') + this.$t('ota.version.moduleName');
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.versionId != null) {
                        updateVersion(this.form).then(response => {
                            this.$modal.updateSuccess();
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        addVersion(this.form).then(response => {
                            this.$modal.addSuccess();
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const versionIds = row.versionId || this.ids;
            const options = this.$t('common.message.tip.confirm', {
              operate: this.$t('common.operate.type.delete'),
              name: this.$t('ota.version.versionId'),
              data: versionIds
            })
            this.$modal.confirm(options).then(() => {
                this.loading = true;
                return delVersion(versionIds);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.deleteSuccess();
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },

        // 下面是文件上传功能
        handleFileSuccess(response, file) {
            console.log(response);
            this.form.versionUrl = response;
        },
        fileChange(file, fileList){
            this.file = file.raw;
            if (fileList.length > 0) {
              this.fileList = [fileList[fileList.length - 1]]; // 获取最后一次选择的文件
            }
        },
        handleStatusChange(row) {
          let text = row.versionState === 1 ? this.$t('common.operate.tip.stop') : this.$t('common.operate.tip.enable');
          this.$modal.confirm(
            this.$t('common.message.tip.confirm', {
            operate: text,
            name: this.$t('ota.version.moduleName'),
            data: row.versionNo})
          )
          .then(function () {
                return changeStatus({ versionId: row.versionId, versionState: row.versionState });
            }).then(() => {
                this.$modal.msgSuccess(text + this.$t('common.operate.tip.success'));
                this.getList();
            }).catch(function () {
                row.versionState = row.versionState === 1 ? 2 : 1;
            })
        }
    }
};
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
</style>
